package flirtme.activities;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.ans.flirtme.R;
import com.ans.flirtme.WakeLocker;
import com.google.android.gcm.GCMRegistrar;

import flirtme.constants.Constants;
import flirtme.fragments.BroadcastMessagesFragment;
import flirtme.fragments.ContactsFragment;
import flirtme.fragments.TabListener;
import flirtme.libraries.utils.Utils;
import flirtme.managers.UserManager;
import flirtme.model.BroadcastContact;
import flirtme.model.BroadcastMessage;
import flirtme.model.ContactModel;
import flirtme.model.Message;
import flirtme.server.UserProfileServices;

public class MainMenuActivity extends Activity {
	ActionBar actionBar;
	
	public void onBackPressed(){
		  //Your code here
		return;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		

		
		//Initialize GPS Position Monitor
		
		//TODO usar macro para saber si se levanta con simulador o con device para uqe no crashee
		// Comento esta linea porque sino al levantar la app con el simulador, me tira un error y se cierra
		//GPSManager.Instance().startLocationReceiver( this ); 
        
		// setup action bar for tabs
	    actionBar = getActionBar();
	    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	   
	    //if (!GCMRegistrar.isRegisteredOnServer(this)) {
	    
	    this.registerGCM();	
	    //}
	    

	    //UserManager um = UserManager.instance();
		//Boolean showBroadcastTab = um.shouldShowBroadcastMessages();
		
	    Tab tab = actionBar.newTab()
	            .setText("Contacts")
	            .setTabListener(new TabListener<ContactsFragment>(
	                    this, "Contacts", ContactsFragment.class));
	    actionBar.addTab(tab);
	    

	   tab = actionBar.newTab()
	    		   .setText("Broadcast")
		            .setTabListener(new TabListener<BroadcastMessagesFragment>(
		                    this, "Broadcast", BroadcastMessagesFragment.class));
		actionBar.addTab(tab);
		

		if (!Utils.runningOnSimulator()) {
			registerReceiver(mHandleMessageReceiver, new IntentFilter(
					Constants.DISPLAY_MESSAGE_ACTION));	
		}
		
		updateBroadcastMessages();
		updateProfileInfo();
		
	}

	private void updateProfileInfo() {
		if (!UserManager.instance().getRememberSession() && !UserManager.instance().isProfileLoaded()) {
			UserProfileServices.callLoadProfileService(this);
		}
		
	}

	private void registerGCM() {
		Boolean isSimulator = Utils.runningOnSimulator();
		if (! isSimulator) {
			
			GCMRegistrar.checkDevice(this);
			GCMRegistrar.checkManifest(this);

			final String regId = GCMRegistrar.getRegistrationId(this);
			
			// Check if regid already presents
			
			if (regId.equals("") || !GCMRegistrar.isRegisteredOnServer(this) ) {
				// Registration is not present, register now with GCM
				GCMRegistrar.register(this, Constants.SENDER_ID);
			}
			else {
				
			}
		}
		
	}
	
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main_menu, menu);
		return true;
	}

	public void refresh () {
		 Tab currentTab = actionBar.getSelectedTab();
		 if (currentTab.getPosition() == 0) {
			ContactsFragment.refreshContacts(this);
		 }
		 else {
			 BroadcastMessagesFragment.getBroadcastMessages(this);
		 }
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		  switch (item.getItemId()) {
		    case R.id.menu_settings:
		    	Intent intent = new Intent();
		        intent.setClass(MainMenuActivity.this, SettingsActivity.class);
		        startActivityForResult(intent, 0); 
		      break;
		    case R.id.action_refresh:
		    	this.refresh();
		      break;

		    default:
		      break;
		    }

		    return true;
	 }

	 @Override
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	  // TODO Auto-generated method stub
	  super.onActivityResult(requestCode, resultCode, data);
	  
	  /*
	   * To make it simple, always re-load Preference setting.
	   */
	  
	 }
	 
	 @Override
	 public void onDestroy()
	 {
         super.onDestroy();
         
        if (!Utils.runningOnSimulator()) {
        	try {
     			unregisterReceiver(mHandleMessageReceiver);
     			GCMRegistrar.onDestroy(this);
        	} catch (Exception e) {
				Log.e("UnRegister Receiver Error", "> " + e.getMessage());
			}
         }
	    // GPSManager.Instance().stopLocationReceiver();
	 }

	 public void viewBroadCastSenderOnMap(View view) {
		Long msgId = (Long) view.getTag();
		BroadcastMessage message = UserManager.instance().getBroadCastMessageById(msgId);
		Location senderLocation =((BroadcastContact) message.getSender()).getLocation();
		
		//Start Map Activity
		Intent intent = new Intent(this, MapActivity.class);
		Bundle b = new Bundle();
		b.putDouble(Constants.LATITUDE_KEY, senderLocation.getLatitude());
		b.putDouble(Constants.LONGITUDE_KEY, senderLocation.getLongitude());
		b.putString(Constants.POSITION_TEXT_KEY, "Lo de Rama ;)"); //message.getSender().getUsername());
		intent.putExtras(b); 
		startActivity(intent);
	 }
	 
	 
	 public void viewContactProfile(View view) {
		 String tag = (String) view.getTag();
		 ContactModel model = UserManager.instance().getContact(tag);
		 if (model != null) {
				//Show Contact Profile
	    		Intent intent = new Intent(this, ShowProfileActivity.class);
	    		Bundle b = new Bundle();
	    		b.putString(Constants.EMAIL, model.getEmail());
	    		b.putString(Constants.USER_NAME, model.getUsername());
	    		b.putString(Constants.AGE, model.getAge());
	    		b.putString(Constants.INTERESTS, model.getInterests());
	    		b.putString(Constants.FIRST_NAME, model.getFirstname());
	    		b.putString(Constants.LAST_NAME, model.getLastname());
	    		b.putString(Constants.INTERESTS, model.getInterests());
	    		b.putString(Constants.BIRTH_DATE,model.getBirthDate());
	    		b.putString(Constants.AVATAR_URL, model.getImageUrl());
	    		b.putString(Constants.GENDER, model.getGender());
	    		intent.putExtras(b); 
	    		this.startActivity(intent);

		 }		    
	 }
	 
	 private void updateBroadcastMessages()
	 {
		 
	 }

	 
		/**
		 * Receiving push messages
		 * */
		private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String newMessage = intent.getExtras().getString(Constants.EXTRA_MESSAGE);
				// Waking up mobile if it is sleeping
				WakeLocker.acquire(getApplicationContext());
			
				
				
				// Releasing wake lock
				WakeLocker.release();
				
				
				
			}
		};
		

		public static void toastMessageWithText(Context context, int text) {
			Toast.makeText(context, text, Toast.LENGTH_LONG).show();
		}
		
		
		
}